<template>
  <view class="order-list-container">
    <status-bar bgColor="#0088ff"></status-bar>
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-title">订单</view>
    </view>
    
    <view class="filter-tabs">
      <view 
        class="tab-item" 
        v-for="(tab, index) in tabs" 
        :key="index" 
        :class="{ active: currentTab === index }"
        @click="switchTab(index)"
      >
        {{ tab }}
      </view>
    </view>
    
    <!-- 使用scroll-view实现上拉加载更多 -->
    <scroll-view 
      class="order-list" 
      scroll-y 
      @scrolltolower="loadMore" 
      @refresherrefresh="refresh"
      refresher-enabled
      :refresher-triggered="isRefreshing"
      lower-threshold="50"
    >
      <block v-for="(order, index) in displayOrderList" :key="index">
        <!-- 订单项 -->
        <view class="order-item">
          <!-- 预约时间或距预约结束时间 -->
          <view class="appointment-time">
            <template v-if="order.status === '待预约' && order.remainingTime">
              <text>距预约结束：</text>
              <text class="time-value">{{order.remainingTime}}</text>
            </template>
            <template v-else>
              <text>预约时间：</text>
              <text class="time-value">{{order.appointmentTime || order.serviceTime || order.verifyTime || ''}}</text>
            </template>
          </view>
          
          <!-- 订单编号和标签 -->
          <view class="order-header">
            <view class="order-no-container">
              <text class="order-no">订单编号：{{order.orderNo}}</text>
              <view v-if="order.isUrgent" class="order-tag urgent-tag">
                <text class="tag-icon">!</text>
                加急
              </view>
            </view>
          </view>
          
          <!-- 客户信息和服务类型 -->
          <view class="customer-info">
            <view class="customer-left">
              <view class="location-icon">
                <image src="/static/images/icon/location.png" class="icon-img"></image>
              </view>
              <view class="customer-details">
                <view class="customer-name">{{order.customerName}}</view>
                <view class="service-type-tag" :class="getServiceTypeClass(order.serviceType)">{{order.serviceType}}</view>
              </view>
            </view>
            <view class="service-status">
              <text>{{order.status}}</text>
              <text class="price">￥{{order.price}}</text>
            </view>
          </view>
          
          <!-- 地址 -->
          <view class="order-address">
            <text class="address-text">{{order.address}}</text>
          </view>
          
          <!-- 异常信息 -->
          <view class="abnormal-reason" v-if="order.operateDescription">
            <text class="reason-label">备注：</text>
            <text class="reason-text">{{order.operateDescription || ''}}</text>
          </view>
          
          <!-- 查看详情按钮 -->
          <view class="order-footer">
            <button class="detail-btn" @click="handleOrderDetail(order)">查看详情</button>
          </view>
        </view>
      </block>
      
      <!-- 加载状态提示 -->
      <view class="loading-more" v-if="displayOrderList.length > 0">
        <text v-if="isLoading">加载中...</text>
        <text v-else-if="hasMore">上拉加载更多</text>
        <text v-else>没有更多数据了</text>
      </view>
      
      <!-- 空数据提示 -->
      <view class="empty-tip" v-if="displayOrderList.length === 0 && !isLoading">
        <image src="/static/images/empty.png" mode="aspectFit" class="empty-image"></image>
        <text>暂无订单数据</text>
      </view>
    </scroll-view>
    
    <!-- 底部占位，防止内容被tabbar遮挡 -->
    <view class="tabbar-placeholder"></view>
    
    <!-- 使用自定义tabbar -->
    <custom-tabbar :active="1"></custom-tabbar>
  </view>
</template>

<script>
import { ordeList } from '@/api/app/master/order.js'

export default {
  data() {
    return {
      tabs: ['全部', '待预约', '待服务', '待验收', '已完成', '异常订单'],
      currentTab: 0,
      page: 1,
      pageSize: 10,
      hasMore: true,
      isLoading: false,
      isRefreshing: false,
      allOrderList: [],
      displayOrderList: [],
      
      // 备用模拟订单数据（仅在接口调用失败时使用）
      mockOrderList: [],
        
    }
  },
  created() {
    // 初始化数据
    this.initData();
    
    // 监听刷新订单列表的事件
    uni.$on('refreshWorkOrders', this.handleRefreshOrders);
  },
  onLoad(options) {
    // 如果从首页带参跳转，设置默认选中标签
    if (options && typeof options.tab !== 'undefined') {
      const idx = parseInt(options.tab, 10);
      if (!Number.isNaN(idx)) {
        this.currentTab = idx;
        // 根据新tab重新拉取数据
        this.initData();
      }
    }
  },
  onLoad(options) {
    // 接收首页传入的 tab 参数，默认选中“待预约”(index=1)
    if (options && typeof options.tab !== 'undefined') {
      const idx = parseInt(options.tab, 10);
      if (!Number.isNaN(idx)) {
        this.currentTab = idx;
        this.initData();
      }
    }
  },
  onShow() {
    // 从本地存储读取首页传入的默认tab（如“待预约”=1）
    const tab = uni.getStorageSync('workDefaultTab');
    if (tab !== '' && tab !== undefined && tab !== null) {
      const idx = parseInt(tab, 10);
      if (!Number.isNaN(idx)) {
        this.currentTab = idx;
        this.initData();
      }
      uni.removeStorageSync('workDefaultTab');
    }else{
      this.currentTab = 0;
      this.initData();
    }
    uni.hideTabBar()
  },
  onHide() {
    uni.removeStorageSync('workDefaultTab');
  },
  onUnload() {
    // 页面卸载时移除事件监听
    uni.$off('refreshWorkOrders', this.handleRefreshOrders);
  },
  methods: {
    // 处理刷新订单列表事件
    handleRefreshOrders() {
      // 重新加载数据
      this.initData();
    },
    
    // 获取服务类型样式类
    getServiceTypeClass(type) {
      if (type === '窗帘测量') {
        return 'measure-tag'
      } else if (type === '窗帘安装') {
        return 'install-tag'
      }
      return ''
    },
    
    // 姓名脱敏处理
    maskName(name) {
      if (!name) return '';
      if (name.length === 1) return name;
      if (name.length === 2) return name.substring(0, 1) + '*';
      return name.substring(0, 1) + '*'.repeat(name.length - 2) + name.substring(name.length - 1);
    },
    
    // 初始化数据
    initData() {
      this.page = 1;
      this.hasMore = true;
      this.isLoading = false;
      this.displayOrderList = [];
      this.fetchOrderList();
    },
    
    // 切换标签
    switchTab(index) {
      if (this.currentTab === index) return;
      this.currentTab = index;
      this.initData();
    },
    
    // 下拉刷新
    refresh() {
      this.isRefreshing = true;
      this.initData();
      setTimeout(() => {
        this.isRefreshing = false;
      }, 1000);
    },
    
    // 上拉加载更多
    loadMore() {
      if (this.isLoading || !this.hasMore) return;
      this.page++;
      this.fetchOrderList();
    },
    
    // 获取订单列表数据
    fetchOrderList() {
      this.isLoading = true;
      
      // 构建请求参数
      const params = {
        pageNum: this.page,
        pageSize: this.pageSize
      };
      
      // 根据当前标签筛选数据
      if (this.currentTab !== 0) {
        const statusMap = {
          1: '2', // 待预约
          2: '3', // 待服务
          3: '4', // 待验收
          4: '5', // 已完成
          5: '99' // 异常订单
        };
        
        if (statusMap[this.currentTab]) {
          params.orderStatus = statusMap[this.currentTab];
        }
      }
      
      // 调用接口获取订单数据
      ordeList(params).then(res => {
        if (res.code === 200) {
          // 获取数据成功
          const orders = res.rows || [];
          this.total = res.total || 0;
          
          // 判断是否还有更多数据
          this.hasMore = this.page * this.pageSize < this.total;
          
          if (orders.length === 0 && this.page === 1) {
            this.noData = true;
          }
          
          // 处理返回的数据
          const processedOrders = orders.map(item => {
            // 格式化预约时间为 yyyy-MM-dd HH:mm
            let formattedTime = '';
            if (item.reservationTime) {
              const dateTime = new Date(item.reservationTime);
              if (!isNaN(dateTime.getTime())) {
                const year = dateTime.getFullYear();
                const month = (dateTime.getMonth() + 1).toString().padStart(2, '0');
                const day = dateTime.getDate().toString().padStart(2, '0');
                const hours = dateTime.getHours().toString().padStart(2, '0');
                const minutes = dateTime.getMinutes().toString().padStart(2, '0');
                formattedTime = `${year}-${month}-${day} ${hours}:${minutes}`;
              } else {
                formattedTime = item.reservationTime;
              }
            }
            
            // 获取订单状态文本
            const statusMap = {
              '1': '待派单',
              '2': '待预约',
              '3': '待服务',
              '4': '待验收',
              '5': '已完成',
              '9': '已售后',
              '99': '异常订单'
            };
            
            return {
              id: item.id || '',
              orderNo: item.orderNo || '',
              appointmentTime: formattedTime,
              serviceTime: item.serviceTime || '',
              verifyTime: item.verifyTime || '',
              tag: item.urgent == 1 ? '加急' : '',
              isUrgent: item.urgent == 1,
              customerName: item.ownerName ? this.maskName(item.ownerName) : '',
              serviceType: item.orderType == '1' ? '窗帘测量' : '窗帘安装',
              address: item.ownerProvincial + item.ownerCity + item.ownerCounty + item.ownerAddress || '',
              price: item.masterOrderFee || '0.00',
              status: statusMap[item.orderStatus] || '待处理',
              exceptionInfo: item.exceptionInfo || '',
              remainingTime: item.remainingTime || (item.orderStatus === '2' ? '24小时' : ''), // 距预约结束时间
              orderNotes: item.orderNotes || '', // 异常原因
              operateDescription: item.operateDescription || '',
            };
          });
          
          // 更新显示的数据
          if (this.page === 1) {
            this.displayOrderList = processedOrders;
          } else {
            this.displayOrderList = [...this.displayOrderList, ...processedOrders];
          }
        } else {
          // 获取数据失败
          uni.showToast({
            title: res.msg || '获取订单数据失败',
            icon: 'none'
          });
          
          // 使用模拟数据作为备用
          if (this.page === 1) {
            this.useMockData();
          }
        }
      }).catch(err => {
        console.error('获取订单数据失败:', err);
        uni.showToast({
          title: '获取订单数据失败，请稍后重试',
          icon: 'none'
        });
        
        // 使用模拟数据作为备用
        if (this.page === 1) {
          this.useMockData();
        }
      }).finally(() => {
        this.isLoading = false;
      });
    },
    // 传入两个值，返回较大值
  compareMax(a, b) {
    // 容错处理：如果其中一个为 null/undefined，返回另一个
    if (a == null) return b;
    if (b == null) return a;

    // 如果需要严格数值比较，可以先把两者转为数字
    const na = Number(a);
    const nb = Number(b);

    // 如果其中一个不是有效数字，直接返回另一个
    if (Number.isNaN(na) && Number.isNaN(nb)) return a; // 或返回 b，视需求而定
    if (Number.isNaN(na)) return b;
    if (Number.isNaN(nb)) return a;

    return na > nb ? a : b;
  },


    // 查看订单详情
    handleOrderDetail(item) {
      console.log(item)
      // 如果订单状态是"待预约"，跳转到预约操作页面
      if (item.status === '待预约' || item.status === '异常订单') {
        uni.navigateTo({
          url: '/pages/order/order-appointment?id=' + item.id
        });
      } 
      // 如果订单状态是"待服务"，跳转到订单详情页面
      else if (item.status === '待服务' || item.status === '待验收' || item.status === '已完成' || item.status === '已售后')   {
        uni.navigateTo({
          url: '/pages/order/order-detail?id=' + item.id
        });
      }
      else {
        // 其他状态的订单暂时只显示提示
        uni.showToast({
          title: '查看订单: ' + item.id,
          icon: 'none'
        });
      }
    },
    
    // 使用模拟数据（在接口调用失败时作为备用）
    useMockData() {
      // 根据当前标签筛选数据
      let filteredList = this.mockOrderList;
      if (this.currentTab !== 0) {
        const statusMap = {
          1: '待派单',
          2: '待预约',
          3: '待服务',
          4: '待验收',
          5: '已完成',
          9: '已售后',
          99: '异常订单'
        };
        
        if (this.currentTab === 5) {
          // 异常订单
          filteredList = this.mockOrderList.filter(item => item.appointmentException);
        } else {
          // 按状态筛选
          filteredList = this.mockOrderList.filter(item => item.status === statusMap[this.currentTab]);
        }
      }
      
      // 生成模拟数据
      let newData = [];
      for (let i = 0; i < this.pageSize; i++) {
        if (filteredList.length > 0) {
          const baseItem = filteredList[i % filteredList.length];
          const newItem = JSON.parse(JSON.stringify(baseItem));
          newItem.orderNo = `A${2025}${String(this.page).padStart(2, '0')}${String(i).padStart(4, '0')}`;
          newData.push(newItem);
        }
      }
      
      // 更新显示的数据
      this.displayOrderList = newData;
      this.hasMore = this.page < 3; // 假设只有3页数据
    }
  }
}
</script>

<style lang="scss" scoped>
.order-list-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 100rpx;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  height: 90rpx;
  background-color: #0088ff;
  color: #fff;
  padding: 0 30rpx;
  position: relative;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  font-weight: bold;
}

.month {
  color: #ffffff;
  font-size: 32rpx;
  position: absolute;
  right: 30rpx;
}

.filter-tabs {
  display: flex;
  background-color: #ffffff;
  padding: 20rpx 0;
  overflow-x: auto;
  white-space: nowrap;
}

.tab-item {
  padding: 10rpx 20rpx;
  margin: 0 10rpx;
  font-size: 28rpx;
  color: #666;
  border-radius: 30rpx;
}

.tab-item.active {
  background-color: #0088ff;
  color: #ffffff;
}

/* 订单列表 */
.order-list {
  flex: 1;
  height: calc(100vh - 90rpx - 80rpx - 100rpx); /* 减去头部、标签栏和底部占位的高度 */
  padding: 20rpx;
}

.order-item {
  background-color: #fff;
  margin-bottom: 20rpx;
  padding: 20rpx;
  position: relative;
  border-radius: 10rpx;
}

/* 预约时间 */
.appointment-time {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
}

.time-value {
  color: #ff8c00;
  font-size: 32rpx;
  font-weight: bold;
}

/* 订单编号和标签 */
.order-header {
  margin-bottom: 20rpx;
}

.order-no-container {
  display: flex;
  align-items: center;
}

.order-no {
  font-size: 28rpx;
  color: #333;
}

.order-tag {
  font-size: 24rpx;
  padding: 4rpx 12rpx;
  border-radius: 6rpx;
  margin-left: 10rpx;
  color: #fff;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.tag-icon {
  display: inline-block;
  width: 20rpx;
  height: 20rpx;
  line-height: 20rpx;
  text-align: center;
  border-radius: 50%;
  background-color: #fff;
  color: #ff3b30;
  font-weight: bold;
  margin-right: 4rpx;
  font-size: 20rpx;
}

.urgent-tag {
  background-color: #ff3b30;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.05);
    opacity: 0.8;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 客户信息和服务类型 */
.customer-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.customer-left {
  display: flex;
  align-items: center;
}

.location-icon {
  width: 50rpx;
  height: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10rpx;
}

.icon-img {
  width: 40rpx;
  height: 40rpx;
}

.customer-details {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.customer-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-right: 15rpx;
}

.service-type-tag {
  font-size: 24rpx;
  padding: 4rpx 16rpx;
  border-radius: 30rpx; /* 使用更大的圆角实现胶囊形状 */
  color: #fff;
  display: inline-block;
  line-height: 1.5;
}

.measure-tag {
  background-color: #4cd964;
}

.install-tag {
  background-color: #007aff;
}

.service-status {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  color: #ff8c00;
}

.price {
  font-size: 36rpx;
  font-weight: bold;
  margin-top: 5rpx;
}

/* 地址 */
.order-address {
  margin-bottom: 20rpx;
  padding-left: 60rpx;
}

.address-text {
  font-size: 28rpx;
  color: #666;
  line-height: 1.4;
}

/* 异常信息 */
.exception-info {
  margin-bottom: 15rpx;
  padding-left: 60rpx;
}

.exception-text {
  font-size: 28rpx;
  color: #ff3b30;
  line-height: 1.4;
}

/* 查看详情按钮 */
.order-footer {
  display: flex;
  justify-content: flex-end;
}

.detail-btn {
  background-color: #fff;
  color: #0088ff;
  font-size: 28rpx;
  padding: 8rpx 30rpx;
  border-radius: 30rpx;
  border: 1px solid #0088ff;
  line-height: 1.5;
  margin: 0;
}

/* 加载状态提示 */
.loading-more {
  text-align: center;
  padding: 20rpx 0;
  font-size: 24rpx;
  color: #999;
}

/* 无数据提示 */
.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  color: #999;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}

/* 底部占位 */
.tabbar-placeholder {
  height: 100rpx;
}

/* 异常原因 */
.abnormal-reason {
  margin-bottom: 20rpx;
  padding: 15rpx;
  background-color: #fff5f5;
  border-radius: 8rpx;
  border-left: 4rpx solid #ff3b30;
}

.reason-label {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.reason-text {
  font-size: 28rpx;
  color: #ff3b30;
}

</style>